<!-- 整个系统的应用 -->
<template>
  <div>
    <!-- <MyTableAlert type="success" message="为了避免数据越权, 应用列表只有平台端才有权限操作"/> -->
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
              <a-menu-item key="2" @click="batchFrozen(2)">
                <Icon icon="ant-design:lock-outlined"></Icon>
                冻结
              </a-menu-item>
              <a-menu-item key="3" @click="batchFrozen(1)">
                <Icon icon="ant-design:unlock-outlined"></Icon>
                解冻
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <!--抽屉-->
    <MicroAppDrawer @register="registerDrawer" @success="handleSuccess"/>
  </div>
</template>

<script lang="ts" name="system-micro-app" setup>
//ts语法
import {ref, unref} from 'vue';
import {ActionItem, BasicTable, TableAction} from '/@/components/Table'
import MicroAppDrawer from './MicroAppDrawer.vue';
import {useDrawer} from '/@/components/Drawer';
import {useListPage} from '/@/hooks/system/useListPage'
import {useMessage} from '/@/hooks/web/useMessage';
import {columns, searchFormSchema} from './microApp.data';
import {batchDeleteMicroApp, deleteMicroApp, frozenBatch, list} from './microApp.api';
import {useRouter} from 'vue-router';
import {useUserStore} from '/@/store/modules/user';

const userStore = useUserStore();
const router = useRouter()

// import { usePermission } from '/@/hooks/web/usePermission'
// const { hasPermission } = usePermission();

const { createMessage, createConfirm } = useMessage();

const selectRows = ref([]);
//注册drawer
const [registerDrawer, { openDrawer }] = useDrawer();
// 列表页面公共参数、方法
const { prefixCls, tableContext } = useListPage({
  designScope: 'micro-app-list',
  tableProps: {
    title: '应用列表',
    api: list,
    bordered: false,
    columns: columns,
    size: 'small',
    formConfig: {
      schemas: searchFormSchema,
    },
    actionColumn: {
      width: 120,
    },
    beforeFetch: (params) => {
      return Object.assign({ 'column': 'createTime', 'order': "desc" }, params)
    },
  }
})


//注册table数据
const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext

/**
 * 新增事件
 */
function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
async function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
async function handleDetail(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  if (record.isAdmin) {
    createMessage.warning('管理员账号不允许此操作！');
    return;
  }
  await deleteMicroApp({ id: record.id }, reload);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  let hasAdmin = unref(selectRows).filter(item => item.isAdmin);
  if (unref(hasAdmin).length > 0) {
    createMessage.warning('管理员账号不允许此操作！');
    return;
  }
  await batchDeleteMicroApp({ ids: selectedRowKeys.value }, () => {
    selectedRowKeys.value = []
    reload()
  })
}
/**
 * 成功回调
 */
function handleSuccess({ isUpdate, values }) {
  reload()
  if (isUpdate) {
    updateTableDataRecord(values.id, values);
    createMessage.success("编辑成功")
  } else {
    createMessage.success("新增成功")
  }
}

/**
 * 冻结解冻
 */
async function handleFrozen(record, status) {
  if (record.isAdmin) {
    createMessage.warning('管理员账号不允许此操作！');
    return;
  }
  await frozenBatch({ ids: record.id, status: status }, reload)
}
/**
* 批量冻结解冻
*/
function batchFrozen(status) {
  createConfirm({
    iconType: 'warning',
    title: '确认操作',
    content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中应用?",
    onOk: async () => {
      await frozenBatch({ ids: unref(selectedRowKeys).join(','), status: status }, reload)
    }
  })
}

const handleOpen = (record) => {
  const appUrl = record.appUrl + '?accessToken=' + userStore.getToken + '&tenantId=' + userStore.getSelectTenant.tenantId
  window.open(appUrl)
}

/**
 * 操作栏
 */
function getTableAction(record): ActionItem[] {
  return [
    {
      label: '进入',
      onClick: handleOpen.bind(null, record),
    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }, 
  ]
}
/**
 * 下拉操作栏
 */
function getDropDownAction(record): ActionItem[] {
  return [
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      },
    }, 
    {
      label: '冻结',
      ifShow: record.status == 1,
      popConfirm: {
        title: '确定冻结吗?',
        confirm: handleFrozen.bind(null, record, "2"),
      },
    }, 
    {
      label: '解冻',
      ifShow: record.status == 2,
      popConfirm: {
        title: '确定解冻吗?',
        confirm: handleFrozen.bind(null, record, "1"),
      },
    }
  ]
}
</script>

<style scoped></style>
